STEP 2: The Select-from-a-list approach

This example makes use of JavaScript to randomize the music file that is to play when the page is loaded, reloaded, or revisited later. Each time the page loads it will play a file which is randomly selected from a list of available files. There is no "memory" used to store the last file that has played, using Cookies or otherwise, so there is a possibility that the same file might be randomly selected twice in a row.

Try loading this page again. You might get a different piece of music. Try this several times.

The select-from-a-list approach makes use of some slightly more advanced JavaScript than the numbered file approach. With this approach you do not need to name the music files in any particular way. All you need to do is create a list of the filenames as they appear in the folder. You then pass this list to the randomFromList function, which then returns a random file from that list. The JavaScript is shown in the source code listing below. Once again, place this JavaScript towards the end of your HTML file, where you'd like the random music file be embedded.

Copy-and-Paste
<SCRIPT SRC="music-object.js"></SCRIPT>

<SCRIPT LANGUAGE=JavaScript><!-- //

function randomFromList () {
   var args = randomFromList.arguments;
   return (args.length == 0) ? '' : args [Math.round (Math.random () * (args.length - 1))];
}

fileToPlay = randomFromList (
   'ambient',
   'classical',
   'house',
   'jungle',
   'lounge',
   'modern-rock',
   'sfx-medley',
   'techno',
   'trance'
);

Music.magicEmbed (
   'SRC="music/' + fileToPlay + '.rmf" ' +
   'AUTOSTART=TRUE ' +
   'DISPLAY=SONG ' +
   'MODE=INFO ' +
   'LOOP=FALSE ' +
   'VOLUME=100'
);

// --></SCRIPT>

In the above script there are two values which must be substituted, and a comma-separated list which must be supplied by you before using the script. These are all highlighted in red.